<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Beerus\Modules\Designer\Actions\EditRemainComboDay;
use Biz\tools\FileUpload;
use Doraemon\cache\UserNick;
use Doraemon\model\Designer\DesignerEquity;
use Doraemon\model\DesignerAmountRecord;
use Doraemon\model\DesignerAuth;
use Doraemon\model\KaDesigner;
use Doraemon\model\KaManage\KaDesignerCombo;
use Doraemon\model\KaManage\KaResourceCombo;
use Doraemon\model\KaManage\KaResourceDetail;
use Doraemon\model\Member;
use Doraemon\pockets\config\IniConfig;
use Doraemon\service\ImageCreate\Schedule;
use Doraemon\service\KaManage\Combo;
use Doraemon\service\KaManage\Resource;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\tools\Curl as DCurl;
use Doraemon\tools\Log;
use Doraemon\tools\ParamsCheck;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\model\Designer;
use Beerus\Modules\Designer\Actions\DownFile;
use Beerus\Modules\Designer\Actions\CollectAmountRecord;
use Beerus\Modules\Designer\Actions\SetEffect;
use Beerus\Modules\Designer\Actions\ForcedEffect;
use Beerus\Modules\Designer\Actions\ContractArchive;
use Beerus\Modules\Designer\Actions\ForcedEffect0;
use Biz\pockets\excel\DownExcel;
use Beerus\Modules\Designer\Actions\DeleteOrder;

/**
 * KA设计师
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class KaDesignerController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // KA设计师列表
    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (!empty($request_data['nick'])) {
            //$uid = User::getUidByNick($request_data['nick']);
            //$condition['uid'] = $uid;
	        $uids = self::searchByNick($request_data['nick']);
	        if (empty($uids)) {
	        	$condition['uid'] = '';
	        } else {
	        	$condition['uid'] = $uids;
	        }
        }

        if (!empty($request_data['service_start_time']['start'])) {
        	$condition['start_time[>=]'] = strtotime($request_data['service_start_time']['start']);
        }

	    if (!empty($request_data['service_start_time']['end'])) {
		    $condition['start_time[<=]'] = strtotime($request_data['service_start_time']['end'] .' 23:59:59');
	    }

	    if (!empty($request_data['service_end_time']['start'])) {
		    $condition['end_time[>=]'] = strtotime($request_data['service_end_time']['start']);
	    }

	    if (!empty($request_data['service_end_time']['end'])) {
		    $condition['end_time[<=]'] = strtotime($request_data['service_end_time']['end'] .' 23:59:59');
	    }

	    if (!empty($request_data['main_area'])) {
		    $condition['main_area[~]'] = $request_data['main_area'];
	    }

	    if ($request_data['data_status'] == '') {
		    $condition['data_status[!]'] = KaDesigner::STATUS_DELETE;
	    } else {
		    $condition['data_status'] = $request_data['data_status'];
	    }

	    if (!empty($request_data['is_archive'])) {
		    $condition['is_archive'] = $request_data['is_archive'];
	    }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = KaDesigner::select('*', $condition);
        foreach ($lists as $key => $value){
            //处理已收款金额
            $lists[$key]['received_amount'] = self::getReceivedAmount($value['contract_number']);
            // 处理KA广告套餐
            if (!empty($value['adv_combo_id'])) {
                $kaAdvComboItem = KaResourceCombo::getComboInfo($value['adv_combo_id']);
                if (!empty($kaAdvComboItem)) {
                    $lists[$key]['adv_combo'] = $kaAdvComboItem['combo_type'].'-'.$kaAdvComboItem['combo_name'];
                }
            }
        }

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = KaDesigner::count('*', $condition);
            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
            }
            unset($item);
        }

        unset($condition['LIMIT']);
	    $search_params = http_build_query($condition);
        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->setActionClass(DropdownActions::class);

	            // 添加导出按钮
	            $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
		            $url = url('/admin/Designer/export1?'. $search_params);
		            $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出KA订单</span></a>
                    </div>';
		            $tool->append($button);

		            $url = url('/admin/Designer/export2?'. $search_params);
		            $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出KA收款记录</span></a>
                    </div>';
		            $tool->append($button);
	            });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
	                $filter->column(1 / 3, function ($filter) {
		                $filter->equal('main_area', '投放城市')->placeholder('请输入城市名称');
	                });
	                $filter->column(1 / 2, function ($filter) {
		                $filter->equal('data_status', '订单状态')->select(KaDesigner::FILTER_STATUS);
	                });
	                $filter->column(1 / 2, function ($filter) {
		                $filter->equal('is_archive', '合同是否归档')->select(KaDesigner::ARCHIVE);
	                });
	                $filter->column(1 / 2, function ($filter) {
		                $filter->between('service_start_time', '服务开始时间')->date();
	                });
	                $filter->column(1 / 2, function ($filter) {
		                $filter->between('service_end_time', '服务结束时间')->date();
	                });

                    $filter->expand();
                });

                $grid->column("uid", '用户UID');
                $grid->column('nick', '用户昵称');

                $grid->column('main_area','投放城市');

                $grid->column("start_time", '服务开始时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->start_time);
                });
                $grid->column("end_time", '服务结束时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->end_time);
                });
                $grid->column('adv_combo', 'KA广告套餐');
                $grid->column('contract_number','合同编号');

                $grid->column("remark", '备注');

                $grid->column("contract_amount", '合同金额')->display(function () {
                    return number_format($this->contract_amount,2);
                });

                $grid->column("received_amount", '已收款金额')->display(function () {
                    return number_format($this->received_amount,2);
                });

                $grid->column("add_time", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                });

                $grid->column("edit_time", '修改时间')->display(function () {
                    if (empty($this->edit_time)) {
                        return '';
                    }
                    return date("Y-m-d H:i:s", $this->edit_time);
                });

                $grid->column("data_status", '数据状态')->display(function () {
                    return KaDesigner::LIST_STATUS[$this->data_status];
                });

                $grid->column("is_archive", '合同是否归档')->display(function () {
                    return KaDesigner::ARCHIVE[$this->is_archive];
                });

                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $admin_name = Admin::user()->username;
                    $id = $actions->row->id;
                    $actions->disableDelete();
                    $actions->disableView();
                    //设为生效和强制生效分别处理
                    $ka_info = KaDesigner::getById($id);
                    $status = $ka_info['data_status'];
                    //没有`ka_collect_amount`权限的角色不显示收款录入按钮
                    if (Admin::user()->can('ka_collect_amount')) {
                        $actions->add(new CollectAmountRecord);
                    }
                    if ($status != KaDesigner::STATUS_EFFECT){
                        $contract_number = $ka_info['contract_number'];
                        $contract_amount = $ka_info['contract_amount'];
                        //根据合同编号获取累计金额
                        $condition['contract_number'] = $contract_number;
                        $record_info = DesignerAmountRecord::getAllByCondition($condition);
                        $all_amount = 0;
                        if ($record_info){
                            foreach ($record_info as $value){
                                $all_amount = $all_amount + $value['amount'];
                            }
                        }
                        if ($all_amount > 0 && (float)$all_amount == (float)$contract_amount){
                            $actions->add(new SetEffect);
                        }elseif((float)$all_amount < (float)$contract_amount && $contract_amount!= 0){
                            //没有`ka.effect`权限的角色不显示强制生效按钮
                            if (Admin::user()->can('ka.effect')) {
                                $actions->add(new ForcedEffect);
                            }
                        }elseif ($contract_amount == 0){
                            //没有`ka.effect`权限的角色不显示强制生效按钮
                            if (Admin::user()->can('ka.effect')) {
                                $actions->add(new ForcedEffect0);
                            }
                        }
                        //没有`ka_delete_order`权限的角色不显示删除订单的按钮
                        if (Admin::user()->can('ka_delete_order')) {
                            $actions->add(new DeleteOrder);
                        }
                    }else{
                        $actions->add(new DownFile);
                        $actions->add(new ContractArchive);
                        $actions->add(new EditRemainComboDay);
                    }

                });
            }
        );

        $tab = new Tab();
        $tab->add('KA设计师列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('KA设计师列表')
            ->description(' ')
            ->breadcrumb(['text' => 'KA设计师列表']);
    }

    /**
     * 新增、修改黑名单
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Request $request, Content $content, $id = 0)
    {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '新增KA';
        } else {
            $is_create = false;
            $header = '修改KA';
        }

        $tab = new Tab();
        $tab->add('KA设计师服务信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => 'KA设计师列表',
                'url' => route('ka.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        $data_status = 0;
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = KaDesigner::get('*', ['id' => $id]);
            $data['start_time'] = date('Y-m-d', $data['start_time']);
            $data['end_time'] = date('Y-m-d', $data['end_time']);
            $form = new Form($data);
            $form->hidden('id');
            $data_status = $data['data_status'];
        }
        if ($data_status == KaDesigner::STATUS_EFFECT){
            $form->text('uid', '用户UID')->setWidth(4, 2)->readonly();
            $form->text('contract_number','合同编号')->help('编号与财务台账一致')->readonly();
            $form->text('contract_amount','合同金额')->readonly();
            $form->text('contract_sales','对接销售')->readonly();
        }else{
            $form->text('uid', '用户UID')->setWidth(4, 2)->required('不能为空');
            $form->text('contract_number','合同编号')->required('不能为空')->help('编号与财务台账一致');
            $form->text('contract_amount','合同金额')->required('不能为空');
            $form->text('contract_sales','对接销售')->required('不能为空');
        }
        $form->dateRange('start_time', 'end_time', '服务开始时间-结束时间')->required('不能为空');
        $form->text('customer_name','客户名称')->required('不能为空')->help('请填写合同上的甲方，如：家宅一生（北京）科技有限公司');
        $form->select('adv_combo_id', 'KA广告位套餐')->options($this->getAdvComboOption())->required();
        $form->fileUpload("contract_annex", '合同附件', ['drop_zone_enabled' => false,'allowed_file_extensions' => ["pdf"],'showPreview' =>true])->help('支持上传pdf，最大10M');
        $form->hidden('contract_annex');
        $form->textarea('remark', '备注')->setWidth(4, 2);
//        $form->select('data_status', '数据状态')->default(KaDesigner::STATUS_NORMAL)
//            ->setWidth(4, 2)->options(KaDesigner::LIST_STATUS);

        $form->action('/admin/Designer/ka/save');

        return $form->render();
    }

    public function getAdvComboOption() {
        $advComboOptions = [];
        // 获取ka广告套餐类型
        $allAdvComboList = KaResourceCombo::getAllComboList();
        foreach ($allAdvComboList as $combo) {
            $advComboOptions[$combo['id']] = $combo['combo_type'].'-'.$combo['combo_name'];
        }
        return $advComboOptions;
    }

    /**
     * 保存数据
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $uid = $request['uid'];
        $contract_annex = $request["contract_annex"];
        $contract_number = $request['contract_number'];
        $contract_amount = $request['contract_amount'];
        $customer_name = $request['customer_name'];
        $contract_sales = $request['contract_sales'];
        $adv_combo_id = $request['adv_combo_id'];
        //获取设计师的主要服务地区作为投放城市
        $userInfo = Designer::getInfo($uid);
        //$main_area = Area::locationId2String($userInfo['main_area']);

        $start_time = strtotime($request['start_time']);
        $end_time = strtotime($request['end_time'] .' 23:59:59');
        $data = [
            'uid' => $uid,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'contract_number' => $contract_number,
            'contract_amount' => $contract_amount,
            'customer_name' => $customer_name,
            'contract_annex' => $contract_annex,
            'contract_sales' => $contract_sales,
            'main_area' => $userInfo['main_area_name'],
            'remark' => $request['remark'],
            //'data_status' => $request['data_status'],
            'admin_id' => Admin::user()->id,
            'adv_combo_id' => $adv_combo_id
        ];

        if (strtotime($request['end_time']) < (int)$data['start_time']) {
            $error = new MessageBag([
                'title' => '服务结束时间不得早于开始时间'
            ]);

            return back()->withInput()->with(compact('error'));
        }

        if ($contract_amount < 0){
            $error = new MessageBag([
                'title' => '请填写正确的合同金额'
            ]);

            return back()->withInput()->with(compact('error'));
        }


        $now = time();
        if (isset($request['id'])) {
            $data['edit_time'] = $now;
            $id = $request['id'];
            // 如果服务到期，则可以更改套餐
            $kaOrderInfo = KaDesigner::getKaOrderInfo($id);
            if ($kaOrderInfo['data_status'] == KaDesigner::STATUS_EFFECT) {
                if ($kaOrderInfo['adv_combo_id'] != $adv_combo_id) {
                    $error = new MessageBag([
                        'title' => '该订单已生效不允许修改KA广告套餐'
                    ]);
                    return back()->withInput()->with(compact('error'));
                }
            }
            if ($kaOrderInfo['data_status'] == KaDesigner::STATUS_EFFECT) {
                // 订单开始结束时间更新到另一张套餐表
                KaDesignerCombo::batchUpdateData([
                    'ka_start_time' => $data['start_time'],
                    'ka_end_time' => $data['end_time']
                ], ['designer_uid' => $uid, 'ka_order_id' => $request['id']]);
            }
            $rs = KaDesigner::updateById($id, $data);
        } else {
            if ($data['start_time'] < strtotime(date('Y-m-d'))) {
                $error = new MessageBag([
                    'title' => '服务开始生效时间不能早于当天'
                ]);

                return back()->withInput()->with(compact('error'));
            }

            if ($contract_amount < 0){
                $error = new MessageBag([
                    'title' => '请填写正确的合同金额'
                ]);

                return back()->withInput()->with(compact('error'));
            }
            //如果是新增的情况,判断合同编号是否已经存在过,如果存在不允许新增
            $condition['contract_number'] = $contract_number;
            $condition['data_status[!]'] = KaDesigner::STATUS_DELETE;
            $ka_info = KaDesigner::getByCondition($condition);
            if ($ka_info){
                $error = new MessageBag([
                    'title' => '该订单已经存在啦,不要重复录入哦!'
                ]);

                return back()->withInput()->with(compact('error'));
            }
            $data['add_time'] = $now;
            $rs = KaDesigner::create($data);

        }

        if ($rs) {
            if (isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);

            return redirect('/admin/Designer/ka')->with(compact('success'));
        } else {
            if (isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }

            $error = new MessageBag([
                'title' => $title
            ]);

            return back()->with(compact('error'));
        }
    }

    public static function getReceivedAmount($contract_number){
        //根据合同编号获取累计金额
        $condition['contract_number'] = $contract_number;
        $record_info = DesignerAmountRecord::getAllByCondition($condition);
        $all_amount = 0;
        if ($record_info){
            foreach ($record_info as $value){
                $all_amount = $all_amount + $value['amount'];
            }
        }
        return $all_amount;
    }

    public static function DownPdfFile($id){
        $ka_info = KaDesigner::getById($id);
        $filename = $ka_info['contract_annex'];
        //进行合同下载操作
        if ($filename) {
            $content = FileUpload::getFile($filename);
            $tmpFile = '/tmp/' . $filename;
            file_put_contents($tmpFile, $content);
            if (file_exists($tmpFile)) {
                $fp = fopen($tmpFile, "r");
                $file_size = filesize($tmpFile);
                header('Content-type: application/pdf');
                //header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . $filename);
                header('Content-Transfer-Encoding: binary');
                header('Content-Length: ' . $file_size);

                $buffer = 1024;
                $file_count = 0;
                while (!feof($fp) && $file_count < $file_size) {
                    $file_con = fread($fp, $buffer);
                    $file_count += $buffer;
                    echo $file_con;
                }
                fclose($fp);
                if ($file_count >= $file_size) {
                    unlink($tmpFile);
                }
            }
        }
    }

	/**
	 * 导出KA订单
	 * @param Request $request
	 */
	public function exportKaOrder(Request $request)
	{
		$request_data = $request->all();

		$condition = [];
		if (!empty($request_data['uid'])) {
			$condition['uid'] = $request_data['uid'];
		}

		if (!empty($request_data['nick'])) {
//			$uid = User::getUidByNick($request_data['nick']);
//			$condition['uid'] = $uid;

			$uids = self::searchByNick($request_data['nick']);
			if (empty($uids)) {
				$condition['uid'] = '';
			} else {
				$condition['uid'] = $uids;
			}
		}

		if (!empty($request_data['start_time'])) {
			if (!empty($request_data['start_time']['>='])) {
				$condition['start_time[>=]'] = $request_data['start_time']['>='];
			}
			if (!empty($request_data['start_time']['<='])) {
				$condition['start_time[<=]'] = $request_data['start_time']['<='];
			}
		}

		if (!empty($request_data['end_time'])) {
			if (!empty($request_data['end_time']['>='])) {
				$condition['end_time[>=]'] = $request_data['end_time']['>='];
			}
			if (!empty($request_data['start_time']['<='])) {
				$condition['end_time[<=]'] = $request_data['end_time']['<='];
			}
		}

		if (!empty($request_data['main_area'])) {
			$condition['main_area[~]'] = $request_data['main_area']['~'];
		}

		if (is_array($request_data['data_status'])) {
			$condition['data_status[!]'] = KaDesigner::STATUS_DELETE;
		} else {
			$condition['data_status'] = $request_data['data_status'];
		}

		if (!empty($request_data['is_archive'])) {
			$condition['is_archive'] = $request_data['is_archive'];
		}

		$condition['ORDER'] = ['id' => 'DESC'];

		$lists = KaDesigner::select('*', $condition);
		$lists = is_array($lists) ? $lists : [];

		if (empty($lists)) {
			$error = new MessageBag([
				'title' => '暂无KA订单数据可导出'
			]);

			return back()->with(compact('error'));
		}

		$user_ids = array_column($lists, 'uid');
		$member_info = Member::getUsers($user_ids);

		$data = [];
		foreach ($lists as $item) {
			$data[] = [
				'uid' => $item['uid'],
				'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
				'main_area' => $item['main_area'],
				'start_time' => date('Y-m-d H:i:s', $item['start_time']),
				'end_time' => date('Y-m-d H:i:s', $item['end_time']),
				'contract_number' => $item['contract_number'],
				'contract_amount' => $item['contract_amount'],
				'customer_name' => $item['customer_name'],
				'contract_sales' => $item['contract_sales'],
				'remark' => $item['remark'],
				'status' => KaDesigner::LIST_STATUS[$item['data_status']],
				'is_archive' => KaDesigner::ARCHIVE[$item['is_archive']]
			];
		}

		$header = [
			'用户UID', '用户昵称', '投放城市', '服务开始时间', '服务结束时间', '合同编号', '合同金额（元）', '客户名称', '对接销售', '备注', '订单状态', '合同是否归档',
		];
		$letter = range('A', 'L');
		$excel_obj = new DownExcel();
		$excel_obj->setFileName('KA订单表 - ' . date('YmdHis'));
		$excel_obj->setSheetTitle('KA订单表');

		// 设置列宽
		$widths = [
			'A' => 12,
			'B' => 15,
			'C' => 12,
			'D' => 23,
			'E' => 23,
			'F' => 20,
			'G' => 13,
			'H' => 20,
			'L' => 13
		];

		$excel_obj->setWidth($widths);
		$excel_obj->setDefaultStyleAlignment();

		foreach ($header as $key => $value) {
			$excel_obj->setFrontName($letter[$key]);
//			$excel_obj->setFrontBold("$letter[$key]1");
			$excel_obj->setFrontSize($letter[$key]);
		}

		$excel_obj->create($data, $header);
	}

	/**
	 * 导出KA收款记录
	 * @param Request $request
	 */
	public function exportKaReturn(Request $request)
	{
		$request_data = $request->all();

		$condition = [];
		if (!empty($request_data['uid'])) {
			$condition['uid'] = $request_data['uid'];
		}

		if (!empty($request_data['nick'])) {
//			$uid = User::getUidByNick($request_data['nick']);
//			$condition['uid'] = $uid;

			$uids = self::searchByNick($request_data['nick']);
			if (empty($uids)) {
				$condition['uid'] = '';
			} else {
				$condition['uid'] = $uids;
			}
		}

		if (!empty($request_data['start_time'])) {
			if (!empty($request_data['start_time']['>='])) {
				$condition['start_time[>=]'] = $request_data['start_time']['>='];
			}
			if (!empty($request_data['start_time']['<='])) {
				$condition['start_time[<=]'] = $request_data['start_time']['<='];
			}
		}

		if (!empty($request_data['end_time'])) {
			if (!empty($request_data['end_time']['>='])) {
				$condition['end_time[>=]'] = $request_data['end_time']['>='];
			}
			if (!empty($request_data['start_time']['<='])) {
				$condition['end_time[<=]'] = $request_data['end_time']['<='];
			}
		}

		if (!empty($request_data['main_area'])) {
			$condition['main_area[~]'] = $request_data['main_area']['~'];
		}

		if (is_array($request_data['data_status'])) {
			$condition['data_status[!]'] = KaDesigner::STATUS_DELETE;
		} else {
			$condition['data_status'] = $request_data['data_status'];
		}

		if (!empty($request_data['is_archive'])) {
			$condition['is_archive'] = $request_data['is_archive'];
		}

		$condition['ORDER'] = ['id' => 'DESC'];

		$lists = KaDesigner::select('*', $condition);
		$lists = is_array($lists) ? $lists : [];

		$user_ids = array_column($lists, 'uid');
		$member_info = Member::getUsers($user_ids);

		$data = [];
		foreach ($lists as $item) {
			$returns = DesignerAmountRecord::select('*', [
				'uid' => $item['uid'],
				'contract_number' => $item['contract_number']
			]);

			if (!empty($returns)) {
				foreach ($returns as $return) {
					$data[] = [
						'uid' => $item['uid'],
						'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
						'main_area' => $item['main_area'],
						'start_time' => date('Y-m-d H:i:s', $item['start_time']),
						'end_time' => date('Y-m-d H:i:s', $item['end_time']),
						'contract_number' => $item['contract_number'],
						'contract_amount' => $item['contract_amount'],
						'customer_name' => $item['customer_name'],
						'contract_sales' => $item['contract_sales'],
						'remark' => $item['remark'],
						'is_archive' => KaDesigner::ARCHIVE[$item['is_archive']],
						'return_time' => empty($return['amount_time']) ?  '-' : date('Y-m-d', $return['amount_time']),
						'amount' => $return['amount'],
						'serial_number' => $return['serial_number']
					];
				}
			}
		}

		if (empty($data)) {
			$error = new MessageBag([
				'title' => '暂无收款记录数据可导出'
			]);

			return back()->with(compact('error'));
		}

		$header = [
			'用户UID', '用户昵称', '投放城市', '服务开始时间', '服务结束时间', '合同编号', '合同金额（元）', '客户名称', '对接销售', '备注',
			'合同是否归档', '收款时间', '收款金额（元）', '银行流水号'
		];
		$letter = range('A', 'N');
		$excel_obj = new DownExcel();
		$excel_obj->setFileName('KA订单收款记录表 - ' . date('YmdHis'));
		$excel_obj->setSheetTitle('KA订单收款记录表');

		// 设置列宽
		$widths = [
			'A' => 12,
			'B' => 15,
			'C' => 12,
			'D' => 23,
			'E' => 23,
			'F' => 20,
			'G' => 15,
			'H' => 20,
			'K' => 13,
			'L' => 15,
			'M' => 15,
			'N' => 15
		];

		$excel_obj->setWidth($widths);
		$excel_obj->setDefaultStyleAlignment();

		foreach ($header as $key => $value) {
			$excel_obj->setFrontName($letter[$key]);
			//$excel_obj->setFrontBold("$letter[$key]1");
			$excel_obj->setFrontSize($letter[$key]);
		}

		$excel_obj->create($data, $header);
	}

	public static function CreatEquity($id){
	    $ka_info = KaDesigner::getById($id);
	    $uid = $ka_info['uid'];
        $start_time = strtotime($ka_info['start_time']);
        $end_time = strtotime($ka_info['end_time'] .' 23:59:59');
        $bypass_equity = DesignerEquity::get('*', [
            'uid' => $uid,
            'equity_type' => DesignerEquity::TYPE_BYPASS
        ]);

        $data = [
            'uid' => $uid,
            'equity_type' => DesignerEquity::TYPE_BYPASS,
            'data_status' => KaDesigner::STATUS_NORMAL
        ];

        if (($end_time - $start_time) > 365*12*3600) {
            $data['adm_num'] = 5;
            $data['remark'] = 'KA一年包自动增加';
        } else {
            $data['adm_num'] = 2;
            $data['remark'] = 'KA半年包自动增加';
        }
        $designer_info = DesignerAuth::getByUId($uid);
        $designer_type = $designer_info['designer_type'];

        if ($designer_type == DesignerAuth::DESIGNER_TYPE_COMPANY){
            if (empty($bypass_equity)) {
                $data['add_time'] = time();

                DesignerEquity::create($data);
            } else {
                $data['edit_time'] = time();

                DesignerEquity::update($data, [
                    'id' => $bypass_equity['id']
                ]);
            }
        }
    }

	public function searchByNick($keyword)
	{
		$config = IniConfig::getConfigSelect('search_mod', 'user');
		$path = $config['host'] . "/list";

		$uid =  UserNick::nick2uid($keyword);

		$filter['nick'] = $keyword;
		$filter['nosegment'] = 1;
		$filter['page'] = 1;
		$filter['pagesize'] = 30;
		$data = DCurl::Request("POST", $path, ['form_params'=> $filter]);
		$data = json_decode($data['data'], true);
		$total = $data['data']['total'];
		$uids = $data['data']['rows'];

		if ($uid) {
			$total = $total + 1;
			array_unshift($uids, $uid);
		}

		return $uids;
	}

    public function editRemainCombo(Request $request, Content $content, $id = 0) {
        $contractInfo = KaDesigner::getById($id);
        $data = KaResourceCombo::get('*', ['id' => $contractInfo['adv_combo_id']]);
        if ($data) {
            $data['ka_order_id'] = $id;
            $data['combo_setting'] = json_decode($data['combo_setting'], true);
            // 获取用户剩余投放天数
            foreach ($data['combo_setting'] as &$item) {
                $designerComboInfo = KaDesignerCombo::getResourceDetailComboInfoWithOutType($contractInfo['uid'], $item['resource_detail_id'], $id);
                $item['remain_combo_day'] = $designerComboInfo['remain_combo_day'];
            }
            $data['uid'] = $contractInfo['uid'];
        }
        $form = new Form($data);
        $form->text('id', '套餐ID')->readOnly();
        $form->text('ka_order_id', 'KA订单ID')->readOnly();
        $form->text('uid', '用户uid')->readOnly();
        $form->text('combo_type', '套餐类型')->readOnly();
        $form->text('combo_name', '套餐名称')->readOnly();
        $form->table('combo_setting', '套餐天数设置', function ($table) use ($data) {
            static $num = -1;
            $table->select('resource_type', '资源位类型')
                ->options(KaResourceCombo::RESOURCE_DETAIL_TITLE)
                ->load('resource_detail_id', '/admin/DesignerAdv/combo/resourceDetail')
                ->readonly();
            $resourceType = $num < 0 ? '' : $data['combo_setting'][$num]['resource_type'];
            $num ++;
            $table->select('resource_detail_id', '资源位对应位置')
                ->options(Resource::getAllResourceDetailList($resourceType))
                ->readonly();
            $table->text('remain_combo_day', '剩余投放天数');
        })->disableCreate()->disableDelete();
        $form->confirm('确定提交吗？');
        $form->action('/admin/Designer/remiancombo/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => 'KA广告套餐列表'],
                ['text' => '编辑套餐信息'],
            )->row($tab);
    }

    public function editRemainComboSubmit(Request $request) {
        $uid = $request->input('uid');
        $comboSetting = $request->input('combo_setting');
        $kaOrderId = $request->input('ka_order_id');
        $comboSetting = array_values($comboSetting);
        foreach ($comboSetting as $combo) {
            if (!ParamsCheck::isPositiveNumber($combo['remain_combo_day'])) {
                $error = new MessageBag(['title' => '套餐天数请输入正数']);
                return back()->with(compact('error'));
            }
        }

        foreach ($comboSetting as $item) {
            $designerComboInfo = KaDesignerCombo::getResourceDetailComboInfoWithOutType($uid, $item['resource_detail_id'], $kaOrderId);
            if ($designerComboInfo && $designerComboInfo['remain_combo_day'] != $item['remain_combo_day']) {
                if (!KaDesignerCombo::updateInfo(['remain_combo_day' => $item['remain_combo_day']], [
                    'designer_uid' => $uid,
                    'resource_detail_id' => $item['resource_detail_id'],
                    'ka_order_id' => $kaOrderId,
                    'data_status' => KaDesignerCombo::STATUS_NORMAL
                ])) {
                    $error = new MessageBag(['title' => '更新失败']);
                    return back()->with(compact('error'));
                }
            }
        }
        Log::info('权益被调整', ['uid' => $uid, 'combo_setting'=>$comboSetting, 'admin_id' => Admin::user()->id]);
        $success = new MessageBag(['title' => '操作成功']);
        return redirect('/admin/Designer/ka')->with(compact('success'));
    }
}
